package com.liuc.practice.ipersistent.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Element;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.util.List;
import java.util.Properties;

/**
 * 该类用于封装 DataSource 对象
 *
 * @Author Liu Chang
 * @Date 2020/12/13 7:03 上午
 */
public class DataSourceBuilder {
    /**
     * 目的：封装数据源对象
     * 步骤：
     * 1. 继续解析 <dataSource></dataSource> 中的内容并封装为 Properties 对象
     * 2. 通过 Properties 对象转换为数据源对象(数据源对象由数据库连接池管理)
     * 3. 返回数据源对象
     * @param elements
     * @return
     */
    public static DataSource build(List<Element> elements) throws PropertyVetoException {
        Properties properties = parse(elements);
        return convert2DataSource(properties);
    }

    private static DataSource convert2DataSource(Properties properties) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();

        dataSource.setDriverClass(properties.getProperty("driverClass"));
        dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));

        return dataSource;
    }

    private static Properties parse(List<Element> elements) {
        Properties properties = new Properties();

        for (Element element : elements) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }
        return properties;
    }
}
